# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from django.template import loader, Context
from django.contrib.admin.models import User
from django.db.models.query_utils import Q
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseNotModified
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getCURoleId, getCompanyTuple
from website.constant import SUPER_POWER
from website.employecontrol.models import Employe
from website.financecontrol.models import SalaryMain, SalaryTCDetail, \
    SalaryCourseTimesDetail, SalaryTrusteeshipDetail, CompanyTask, \
    SalaryCourseTimesManagerDetail


@csrf_exempt
def salary(request):
#    limit=request.GET['limit']
#    page=request.GET['page']
#    start=request.GET['start']
#    print limit ,page,start
    results=User.objects.all();
    return utils.JsonResponse(grids.ModelGrid(User).to_grid(results))


@csrf_exempt
def salarymain_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    name=request.POST.get('name','')
    state=request.POST.get('state','')
    company_id=request.POST.get('company_id','')
#    if getCURoleId(request) ==SUPER_POWER :
#        company_id=request.POST.get('company_id','')
#    else:
#        company_id = getCompanyTuple(request)[0]
    
    q1=Q()
    if company_id<>'':
        q1 &=Q(employe__company=company_id)
    if name <>'':
        q1 &=Q(employe__name__contains=name)
    if state <>'':
        q1 &=Q(state=state)
    
    queryset=SalaryMain.objects.filter(q1)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','month','employe_id','employe__name','employe__department__name','employe__office__name',
              'salarylevel__base_salary','salarylevel__performance_salary','performance_no','salarylevel__secrecy_salary',
              'salarylevel__traffic_subsidy','salarylevel__comm_subsidy',
              'yearfee','monthfee','dayfee',
              'tc_fee','tc_all_fee','course_fee','course_all_fee','trusteeship_fee','call_fee','performance_no','insure_fee',
              'state','remark')),queryset.count()))


@csrf_exempt
def salarymain_export(request):
    name=request.GET.get('name','')
    state=request.GET.get('state','')
    company_id=request.GET.get('company_id','')

    q1=Q()
    if company_id<>'':
        q1 &=Q(employe__company=company_id)
    if name <>'':
        q1 &=Q(employe__name__contains=name)
    if state <>'':
        q1 &=Q(state=state)
    
    queryset=SalaryMain.objects.filter(q1)
    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=工资.xls'
    t = loader.get_template('xls/salarymain_export.html')
    c = Context({'queryset':queryset})
    response.write(t.render(c))
    return response

   
@csrf_exempt
def salarymain_update_state(request):
    # 薪水审核
    ids=request.POST.get('ids','')
    state=request.POST.get('state','')
    
    try:
        if ids <> '':
            salary_ids=ids.rstrip(',').split(',')
            for salary_id in salary_ids:
                salary = SalaryMain.objects.get(id=salary_id)
                salary.state=state
                salary.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'审核成功！'}))



@csrf_exempt
def salarytcdetail_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    month=request.POST.get('month','')

    queryset=SalaryTCDetail.objects.filter(employe=employe_id,month=month)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','trainingcontract_id','trainingcontract__name','course_id','course__name',
                                                                 'e1','e2','rebate','trainingcontract__contract_type',
                                                                 'self_ratio','fee','month','remark','real_e','rebate_fee','study_type')),queryset.count()))
    
@csrf_exempt
def salarycoursetimesdetail_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    month=request.POST.get('month','')

    q = Q(employe=employe_id)
    q |= Q(student_manager=employe_id)
    q &= Q(month=month)

    queryset=SalaryCourseTimesDetail.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','company_id','company__cn_name','student_id','student__name',
                                                                 'grade_id','grade__name','student_manager_id','student_manager__name','student_manager_fee',
                                                                 'employe_id','employe__name','do_time','begin_time','end_time',
                                                                 'course_id','course__name','study_type','course_times','price','ratio',
                                                                 'fee','month','remark')),queryset.count()))

@csrf_exempt
def salarytrusteeshipdetail_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    month=request.POST.get('month','')

    queryset=SalaryTrusteeshipDetail.objects.filter(employe=employe_id,month=month)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','student_id','student__name',
                                                                 'grade_id','grade__name','course_id','course__name','days',
                                                                 'fee','month','remark')),queryset.count()))




@csrf_exempt
def salarycoursetimesmanagerdetail_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    month=request.POST.get('month','')

    q = Q(employe=employe_id)
    q &= Q(month=month)

    queryset=SalaryCourseTimesManagerDetail.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','expect_course','real_course',
                                                                 'real_course_price','ratio','real_fee','student_id',
                                                                 'student__name','grade_id','grade__name','course_id','course__name',
                                                                 'course_times','price','fee','month','remark')),queryset.count()))











#校区任务分解
@csrf_exempt
def companytask_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    company_id=request.POST.get('company_id','')
    q = Q()
    if company_id <> '':
        q &= Q(company=company_id)
    
    queryset=CompanyTask.objects.filter(q)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','company_id','company__cn_name','month',
                                                                 'task_price','task_new','course_expect','course_new')),queryset.count()))


@csrf_exempt
def companytask_save(request):
    task_id=request.POST.get('id','')
    company_id=request.POST.get('company_id','')
    month=request.POST.get('month','')
    task_price=request.POST.get('task_price','')
    task_new=request.POST.get('task_new','')
    course_expect=request.POST.get('course_expect','')
    course_new=request.POST.get('course_new','')
    
    try:
        if task_id=='':
            CompanyTask.objects.create(company_id=company_id,month=month,task_price=task_price,task_new=task_new,
                                       course_expect=course_expect,course_new=course_new)
        else:
            companyTask=CompanyTask.objects.get(id=task_id)
            companyTask.company_id=company_id
            companyTask.month=month
            companyTask.task_price=task_price
            companyTask.task_new=task_new
            companyTask.course_expect=course_expect
            companyTask.course_new=course_new
            companyTask.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':'校区不能选择全部!'+str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def companytask_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            task_ids=ids.split(',')
            for task_id in task_ids:
                CompanyTask.objects.get(id=task_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))


